import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { queryConstellation, queryChineseZodiac } from '../../services/tools';

const Zodiac: React.FC = () => {
  const [activeTab, setActiveTab] = useState<'constellation' | 'chineseZodiac'>('constellation');
  const [constellationCode, setConstellationCode] = useState('');
  const [zodiacCode, setZodiacCode] = useState('');
  const [constellationData, setConstellationData] = useState<any>(null);
  const [zodiacData, setZodiacData] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  
  const navigate = useNavigate();
  
  // 星座选项
  const constellationOptions = [
    { code: 'aries', name: '白羊座 (3.21-4.19)' },
    { code: 'taurus', name: '金牛座 (4.20-5.20)' },
    { code: 'gemini', name: '双子座 (5.21-6.21)' },
    { code: 'cancer', name: '巨蟹座 (6.22-7.22)' },
    { code: 'leo', name: '狮子座 (7.23-8.22)' },
    { code: 'virgo', name: '处女座 (8.23-9.22)' },
    { code: 'libra', name: '天秤座 (9.23-10.23)' },
    { code: 'scorpio', name: '天蝎座 (10.24-11.22)' },
    { code: 'sagittarius', name: '射手座 (11.23-12.21)' },
    { code: 'capricorn', name: '摩羯座 (12.22-1.19)' },
    { code: 'aquarius', name: '水瓶座 (1.20-2.18)' },
    { code: 'pisces', name: '双鱼座 (2.19-3.20)' }
  ];
  
  // 生肖选项
  const zodiacOptions = [
    { code: 'rat', name: '鼠' },
    { code: 'ox', name: '牛' },
    { code: 'tiger', name: '虎' },
    { code: 'rabbit', name: '兔' },
    { code: 'dragon', name: '龙' },
    { code: 'snake', name: '蛇' },
    { code: 'horse', name: '马' },
    { code: 'goat', name: '羊' },
    { code: 'monkey', name: '猴' },
    { code: 'rooster', name: '鸡' },
    { code: 'dog', name: '狗' },
    { code: 'pig', name: '猪' }
  ];
  
  const handleConstellationQuery = async () => {
    if (!constellationCode) {
      setError('请选择星座');
      return;
    }
    
    try {
      setLoading(true);
      setError('');
      
      const response = await queryConstellation(constellationCode);
      
      if (response.code === 200) {
        setConstellationData(response.data);
      } else {
        setError(response.message || '获取星座信息失败');
      }
    } catch (err: any) {
      setError(err.message || '获取星座信息失败，请稍后再试');
    } finally {
      setLoading(false);
    }
  };
  
  const handleZodiacQuery = async () => {
    if (!zodiacCode) {
      setError('请选择生肖');
      return;
    }
    
    try {
      setLoading(true);
      setError('');
      
      const response = await queryChineseZodiac(zodiacCode);
      
      if (response.code === 200) {
        setZodiacData(response.data);
      } else {
        setError(response.message || '获取生肖信息失败');
      }
    } catch (err: any) {
      setError(err.message || '获取生肖信息失败，请稍后再试');
    } finally {
      setLoading(false);
    }
  };
  
  // 模拟星座数据
  const mockConstellationData = {
    name: constellationOptions.find(item => item.code === constellationCode)?.name.split(' ')[0] || '',
    element: ['火象星座', '土象星座', '风象星座', '水象星座'][Math.floor(Math.random() * 4)],
    luckyColor: ['红色', '蓝色', '绿色', '紫色', '黄色'][Math.floor(Math.random() * 5)],
    luckyNumber: Math.floor(Math.random() * 10),
    personality: '性格开朗，热情洋溢，充满活力，喜欢冒险和挑战，但有时过于冲动。',
    loveCompatibility: '与狮子座、射手座最为相配，与天秤座、双子座也能和谐相处。',
    careerAdvice: '适合从事需要创造力和领导力的工作，如市场营销、销售、管理等。',
    todayFortune: '今日运势不错，工作上会有新的机遇，但需注意情绪控制，避免冲动决策。'
  };
  
  // 模拟生肖数据
  const mockZodiacData = {
    name: zodiacOptions.find(item => item.code === zodiacCode)?.name || '',
    years: '1924, 1936, 1948, 1960, 1972, 1984, 1996, 2008, 2020',
    element: ['木', '火', '土', '金', '水'][Math.floor(Math.random() * 5)],
    personality: '聪明机智，反应敏捷，善于社交，但有时过于急躁，缺乏耐心。',
    loveCompatibility: '与龙、猴最为相配，与牛、马、兔也能和谐相处。',
    careerAdvice: '适合从事需要灵活思维和社交能力的工作，如销售、公关、媒体等。',
    yearFortune: '2023年整体运势平稳，事业上有所突破，财运良好，但需注意健康和人际关系。'
  };
  
  const displayConstellationData = constellationData || (constellationCode ? mockConstellationData : null);
  const displayZodiacData = zodiacData || (zodiacCode ? mockZodiacData : null);
  
  return (
    <div className="min-h-screen bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
      <div className="max-w-3xl mx-auto bg-white rounded-xl shadow-md overflow-hidden">
        <div className="p-6">
          <h2 className="text-2xl font-bold text-gray-900 text-center mb-6">星座与生肖查询</h2>
          
          {/* 标签切换 */}
          <div className="flex border-b border-gray-200 mb-6">
            <button
              className={`py-2 px-4 font-medium text-sm focus:outline-none ${
                activeTab === 'constellation'
                  ? 'text-indigo-600 border-b-2 border-indigo-600'
                  : 'text-gray-500 hover:text-gray-700'
              }`}
              onClick={() => setActiveTab('constellation')}
            >
              星座查询
            </button>
            <button
              className={`py-2 px-4 font-medium text-sm focus:outline-none ${
                activeTab === 'chineseZodiac'
                  ? 'text-indigo-600 border-b-2 border-indigo-600'
                  : 'text-gray-500 hover:text-gray-700'
              }`}
              onClick={() => setActiveTab('chineseZodiac')}
            >
              生肖查询
            </button>
          </div>
          
          {error && (
            <div className="text-red-500 text-sm text-center mb-4">
              {error}
            </div>
          )}
          
          {/* 星座查询 */}
          {activeTab === 'constellation' && (
            <div>
              <div className="mb-6">
                <label htmlFor="constellation" className="block text-sm font-medium text-gray-700 mb-2">
                  选择星座
                </label>
                <div className="flex space-x-2">
                  <select
                    id="constellation"
                    className="block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                    value={constellationCode}
                    onChange={(e) => setConstellationCode(e.target.value)}
                  >
                    <option value="">请选择星座</option>
                    {constellationOptions.map(option => (
                      <option key={option.code} value={option.code}>{option.name}</option>
                    ))}
                  </select>
                  <button
                    onClick={handleConstellationQuery}
                    disabled={loading}
                    className={`inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 ${loading ? 'opacity-70 cursor-not-allowed' : ''}`}
                  >
                    {loading ? '查询中...' : '查询'}
                  </button>
                </div>
              </div>
              
              {displayConstellationData && (
                <div className="bg-indigo-50 p-4 rounded-lg">
                  <h3 className="text-xl font-medium text-indigo-900 mb-4">{displayConstellationData.name}</h3>
                  
                  <div className="grid grid-cols-2 gap-4 mb-4">
                    <div>
                      <span className="text-gray-500">所属元素：</span>
                      <span className="font-medium">{displayConstellationData.element}</span>
                    </div>
                    <div>
                      <span className="text-gray-500">幸运色：</span>
                      <span className="font-medium">{displayConstellationData.luckyColor}</span>
                    </div>
                    <div>
                      <span className="text-gray-500">幸运数字：</span>
                      <span className="font-medium">{displayConstellationData.luckyNumber}</span>
                    </div>
                  </div>
                  
                  <div className="space-y-3">
                    <div>
                      <h4 className="text-md font-medium text-indigo-800">性格特点</h4>
                      <p className="text-gray-700">{displayConstellationData.personality}</p>
                    </div>
                    
                    <div>
                      <h4 className="text-md font-medium text-indigo-800">爱情配对</h4>
                      <p className="text-gray-700">{displayConstellationData.loveCompatibility}</p>
                    </div>
                    
                    <div>
                      <h4 className="text-md font-medium text-indigo-800">事业建议</h4>
                      <p className="text-gray-700">{displayConstellationData.careerAdvice}</p>
                    </div>
                    
                    <div>
                      <h4 className="text-md font-medium text-indigo-800">今日运势</h4>
                      <p className="text-gray-700">{displayConstellationData.todayFortune}</p>
                    </div>
                  </div>
                </div>
              )}
            </div>
          )}
          
          {/* 生肖查询 */}
          {activeTab === 'chineseZodiac' && (
            <div>
              <div className="mb-6">
                <label htmlFor="zodiac" className="block text-sm font-medium text-gray-700 mb-2">
                  选择生肖
                </label>
                <div className="flex space-x-2">
                  <select
                    id="zodiac"
                    className="block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                    value={zodiacCode}
                    onChange={(e) => setZodiacCode(e.target.value)}
                  >
                    <option value="">请选择生肖</option>
                    {zodiacOptions.map(option => (
                      <option key={option.code} value={option.code}>{option.name}</option>
                    ))}
                  </select>
                  <button
                    onClick={handleZodiacQuery}
                    disabled={loading}
                    className={`inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 ${loading ? 'opacity-70 cursor-not-allowed' : ''}`}
                  >
                    {loading ? '查询中...' : '查询'}
                  </button>
                </div>
              </div>
              
              {displayZodiacData && (
                <div className="bg-red-50 p-4 rounded-lg">
                  <h3 className="text-xl font-medium text-red-900 mb-4">{displayZodiacData.name}</h3>
                  
                  <div className="grid grid-cols-2 gap-4 mb-4">
                    <div>
                      <span className="text-gray-500">对应年份：</span>
                      <span className="font-medium">{displayZodiacData.years}</span>
                    </div>
                    <div>
                      <span className="text-gray-500">五行属性：</span>
                      <span className="font-medium">{displayZodiacData.element}</span>
                    </div>
                  </div>
                  
                  <div className="space-y-3">
                    <div>
                      <h4 className="text-md font-medium text-red-800">性格特点</h4>
                      <p className="text-gray-700">{displayZodiacData.personality}</p>
                    </div>
                    
                    <div>
                      <h4 className="text-md font-medium text-red-800">相配生肖</h4>
                      <p className="text-gray-700">{displayZodiacData.loveCompatibility}</p>
                    </div>
                    
                    <div>
                      <h4 className="text-md font-medium text-red-800">事业建议</h4>
                      <p className="text-gray-700">{displayZodiacData.careerAdvice}</p>
                    </div>
                    
                    <div>
                      <h4 className="text-md font-medium text-red-800">本年运势</h4>
                      <p className="text-gray-700">{displayZodiacData.yearFortune}</p>
                    </div>
                  </div>
                </div>
              )}
            </div>
          )}
          
          {/* 操作按钮 */}
          <div className="mt-8 flex justify-center">
            <button
              onClick={() => navigate('/tools')}
              className="inline-flex items-center px-4 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
            >
              返回工具列表
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Zodiac;
